package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("分页查询")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        log.info("菜品分页查询：{}", dishPageQueryDTO);
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 新增菜品和口味数据
     * @param dishDTO
     * @return
     */
    @ApiOperation("新增菜品")
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品：{}", dishDTO);
        dishService.saveDishAndFlvors(dishDTO);
        //添加菜品后  清理redis中的缓存
        redisTemplate.delete("dish_" + dishDTO.getCategoryId());
        return Result.success();
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation("批量删除")
    @Transactional(rollbackFor = Exception.class)
    public Result deleteBatch(@RequestParam List<Integer> ids) {
        log.info("批量删除ids：{}",ids);
        //获取菜品菜品的状态
        Integer statusCount = dishService.getStatusByIds(ids);
        //判断状态是否为启售
        if (statusCount > 0) {
            //1为启售  启售不能删
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //获取菜品是否关联套餐
        Integer setmealCount = setmealDishService.getSetmealCountByIds(ids);
        if (setmealCount > 0) {
            //关联套餐  不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //批量删除菜品
        dishService.deleteBatch(ids);

        //批量删除口味
        dishFlavorService.deleteBatch(ids);
        deleteCache("dish_*");
        return Result.success();
    }

    /**
     * 回显菜品数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("回显菜品数据")
    public Result getDishById(@PathVariable("id") Long id) {
        log.info("根据id查询菜品信息：{}", id);
        DishVO dishVO = dishService.getDishById(id);
        return Result.success(dishVO);
    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品信息:{}", dishDTO);
        dishService.updateWithFlavors(dishDTO);
        redisTemplate.delete(dishDTO.getCategoryId());
        return Result.success();
    }

    /**
     * 修改菜品状态
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("修改菜品状态")
    public Result updateWithStatus(@RequestParam Long id, @PathVariable("status") Integer status) {
        log.info("修改菜品状态：{},当前菜品为id：{}", status, id);
        dishService.updateWithStatus(id, status);

       /* //获取缓存中dish开头的key
        Set keys = redisTemplate.keys("dish_*");
        //删除带有dish开头的缓存数据
        redisTemplate.delete(keys);*/
        deleteCache("dish_*");
        return Result.success();
    }

    /**
     * 根据分类id查询菜品数据
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result getDishsByCategoryId(@RequestParam Long categoryId) {
        log.info("根据分类id查询菜品数据,分类id:{}", categoryId);
        List<Dish> dishVOList = dishService.getDishsByCategoryId(categoryId);
        return Result.success(dishVOList);
    }


    /**
     * 统一清理缓存数据
     */
    public void deleteCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);

    }
}
